package com.itheima.health.aspeact;

import com.itheima.health.eume.Time;
import com.itheima.health.autotimeeume.AutoAspectAnn;
import com.itheima.health.common.MessageConst;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDate;



@Component
@Aspect
@Slf4j
public class AutoTime {


    @Before("@annotation(com.itheima.health.autotimeeume.AutoAspectAnn)&&execution(* com.itheima.health.mapper.*.*(..))")
    public void AutoTimeAspect(JoinPoint joinPoint) throws  InvocationTargetException, IllegalAccessException {
        //获得方法标签
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        System.out.println(signature);

        //通过标签获得方法上的注解
        AutoAspectAnn annotation = signature.getMethod().getAnnotation(AutoAspectAnn.class);

        //通过joinPoint拿到方法的参数
        Object[] args = joinPoint.getArgs();
        //获得参数列表的第一个参数
        Object entity = args[0];

        //判断参数是否为空
        if (entity ==null){
            return;
        }
        //定义当前系统时间
        LocalDate now = LocalDate.now();

        //根据注解判断是删除还是新增
        if (annotation.value()== Time.UPDATE){
            try {
                Method updateTime = entity.getClass().getDeclaredMethod(MessageConst.SET_UPDATE_TIME, LocalDate.class);
                updateTime.invoke(entity,now);

                log.info("添加时间段成功");
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                log.error("添加时间失败");
            }

        }else if (annotation.value()==Time.INSERT){
            try {
                Method updateTime = entity.getClass().getDeclaredMethod(MessageConst.SET_CAREDATE_TIME, LocalDate.class);
                Method caretTime = entity.getClass().getDeclaredMethod(MessageConst.SET_UPDATE_TIME,LocalDate.class);
                updateTime.invoke(entity,now);
                caretTime.invoke(entity,now);

                log.info("时间添加成功");
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                log.error("时间添加失败");
            }

        }

    }
}
